/**
 * TetisDB
 *
 * Leitor do properties de configuracao do TetisDomain
 */

package br.com.tetisdb.io.domainConfig;

import br.com.tetisdb.lang.TetisObject;
import br.com.tetisdb.util.TetisUtil;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import br.com.tetisdb.configure.TConfigureDomain;
import br.com.tetisdb.configure.TetisConfigureDomain;
import br.com.tetisdb.domain.TetisDomain;

public class ConfigIOReader extends TetisObject {
    /**
     * Construtor padrao
     */
    public ConfigIOReader() {
    }
    
    /**
     * Resgata a configuracao de um determinado TetisDomain
     *
     * @param domain TetisDomain cuja a configuracao deve ser resgatada
     * @return TetisConfigureDomain Configuracao retornada.
     */
    public TetisConfigureDomain getConfigureDomain(TetisDomain domain) {
        try {
            File file = new File(ConfigIOManager.pathConfig + ConfigIOManager.nameConfig);
            
            if (!file.exists()) {
                ConfigIOManager.writeConfigure(domain);
            }
            
            Properties props = new Properties();
            FileInputStream fis = null;
            
            fis = new FileInputStream(file);
            props.load(fis);
            
            String name = props.getProperty(ConfigIOManager.NAMEDOMAIN);
            TConfigureDomain tc = (TetisUtil.stringIsValid(name) ? new TConfigureDomain(name) : null);
            
            if(tc != null) {
                String sTime = props.getProperty(ConfigIOManager.TIMESNAPSHOT);
                
                if (TetisUtil.stringIsValid(sTime)) {
                    try {
                        tc.setTimeSnapShot(Integer.parseInt(sTime));
                    } catch (Exception e1) {
                        tetisLogger.error("Erro ao ler tempo de snapshot do dominio: "+name+". Erro: "+e1.getMessage(), e1);
                    }
                }
            }
            
            fis.close();
            
            return (TetisConfigureDomain) tc;
            
        } catch (Exception e) {
            tetisLogger.error("Erro ao ler configuracao do dominio. Erro: "+e.getMessage(), e);
            return null;
        }
    }
}
